<?php
//-------------------------------------------------------
// 考核绩效
//-------------------------------------------------------
namespace app\admin\controller;
use think\Controller;
class Kpi extends Controller
{
    /**
     * 运营考核
     * admin/Kpi/motionBusiness
     */
    public function motionBusiness(){
        $groupId = session('group_id','','admin');
        $list = db('check_operator_list')->where('is_del',0)->order('id DESC')->paginate(12)->each(function($item, $key){
            $item['operator'] = db('admin')->where('id','IN',$item['operator_ids'])->value('GROUP_CONCAT(name)');
            return $item;
        });

        $this->assign(['list'=>$list]);
        return view();
    }

    public function motionBusinessContent()
    {
        return view();
    }

    public function motionBusinessAdd()
    {
        if(request()->isAjax())
        {
            $data=input('post.');
            $data['admin_id'] = session('uid','','admin');
            $data['start_time'] = strtotime($data['start_time']);
            $data['end_time'] = strtotime($data['end_time'])+86399;
            $data['operator_ids'] = implode(',',$data['operator_ids']);
            if(input()['id'])
            {
                db('check_operator_list')->where('id',input()['id'])->update($data);
            }
            else
            {
                $data['add_time'] = time();
                db('check_operator_list')->insert($data);
            }
            return ['code'=>1,'msg'=>'操作成功','icon'=>1];
        }
        else
        {
            $operator = db('admin')->where('group_id',7)->where('status',1)->orderRaw('CONVERT(name USING gbk)')->select();
            if(input()['id'])
                $data = db('check_operator_list')->where('id',input()['id'])->find();
            else
                $data['title'] = date('Y年m').'月度运营人员考核';

            $data['start_time'] = $data['start_time']?date('Y-m-d',$data['start_time']):date('Y-m-01');
            $data['end_time'] = $data['end_time']?date('Y-m-d',$data['end_time']):date('Y-m-t');

            $data['operator_ids'] = explode(',',$data['operator_ids']);
            $this->assign(['data'=>$data,'operator'=>$operator]);
            return view();
        }
    }

    public function motionBusinessDel()
    {
        $id = input('id');
        if($id && session('group_id','','admin') == 1)
        {
            db('check_operator_list')->where('id',$id)->update(['is_del'=>1]);
            return ['code'=>1,'msg'=>'操作成功','icon'=>1];
        }
    }

    public function motionBusinessDo()
    {
        $adminId = session('uid','','admin');

        //$adminId = 14;
        $info = db('check_operator_list')->where('is_del',0)->where('id',input()['check_id'])->find();
        if(request()->isAjax())
        {
            $data = input('post.');
            $data['add_time'] = time();
            $data['admin_id'] = $adminId;
            return db('check_operator_info')->insert($data)?['code'=>1,'msg'=>'操作成功','icon'=>1]:['code'=>-1,'msg'=>'操作失败','icon'=>2];
        }
        else
        {
            $pageList = db('active_page_log')->where('to_admin_id',$adminId)->where('complete_time','>=',$info['start_time'])->where('complete_time','<=',$info['end_time'])->select();

            if($pageList)
            {
                foreach ($pageList as $k=>$v)
                {
                    if(!db('check_operator_info')->where('check_id',$info['id'])->where('admin_id',$adminId)->where('operator_id',$v['admin_id'])->value('id'))
                        $pageListN[$v['admin_id']]['list'][] = $v;
                }
                if($pageListN)
                {
                    foreach ($pageListN as $k=>$v)
                    {
                        $pageListN[$k]['name'] = db('admin')->where('id',$k)->value('name');
                    }
                }
            }
            $this->assign(['score_1'=>[2,6,8],'score_2'=>[1,3,4,5,7,9,10],'score_3'=>[11],'pageListN'=>$pageListN ,'info'=>$info ]);
            return view();
        }

    }

    public function motionBusinessStats()
    {
        $checkId = input()['check_id'];
        if($checkId)
        {
            $info = db('check_operator_list')->where('is_del',0)->where('id',$checkId)->find();
            $list = db('admin')->where('id','IN',$info['operator_ids'])->select();

            foreach ($list as $k=>$v)
            {
                $list[$k]['page_count'] = 0;
                $list[$k]['result'] = db('check_operator_info')->field('CAST(AVG(score_total) AS DECIMAL(10,1)) as score_total,sum(veto_1) as veto_1,sum(veto_2) as veto_2,sum(veto_3) as veto_3 ')->where('check_id',$checkId)->where('operator_id',$v['id'])->find();

                $childList = db('active_page_log')->field('staff_name,to_admin_id')->where('admin_id',$v['id'])->where('complete_time','>=',$info['start_time'])->where('complete_time','<=',$info['end_time'])->group('to_admin_id')->select();
                foreach($childList as $kk=>$vv)
                {
                    $childList[$kk]['result'] = db('check_operator_info')->alias('i')->field('i.*,a.name')->join('admin a','a.id=i.admin_id')->where('i.check_id',$checkId)->where('i.operator_id',$v['id'])->where('i.admin_id',$vv['to_admin_id'])->order('id ASC')->find();
                    $childList[$kk]['result']['page_count'] = db('active_page_log')->where('admin_id',$v['id'])->where('to_admin_id',$vv['to_admin_id'])->where('complete_time','>=',$info['start_time'])->where('complete_time','<=',$info['end_time'])->count();
                    $list[$k]['page_count'] += $childList[$kk]['result']['page_count'];
                }
                $list[$k]['list'] = $childList;

                /*
                $list[$k]['list'] = db('check_operator_info')->alias('i')->field('i.*,a.name')->join('admin a','a.id=i.admin_id')->where('i.check_id',$checkId)->where('i.operator_id',$v['id'])->order('id ASC')->select();

                $otherList = db('active_page_log')->where('to_admin_id','NOT IN',db('check_operator_info')->where('check_id',$checkId)->where('operator_id',$v['id'])->value('GROUP_CONCAT(admin_id)') )->where('admin_id',$v['id'])->where('add_time','>=',$info['start_time'])->where('add_time','<=',$info['end_time'])->group('to_admin_id')->select();
                */
            }
        }
        $this->assign(['list'=>$list ,'info'=>$info ]);
        return view();
    }


//--------------------------------------------------------------------------------------------------------------------------
    /**
     * @author  ShuAnG
     * @createDate  2023-03-13
     * 考核栏目管理--列表
     * @return mixed
     */
    public function columnList(){
        if(input()['limit'])
        {
            $page = input()['page']?:1;
            $limit = input()['limit']?:1;
            $db = Db('kpi_column');
            $count = $db;

            if(input('keyword'))
            {
                $keyWord = input('keyword');
                //姓名、身份证、家庭住址、手机号、紧急联系人姓名、紧急联系人手机号
                $list_arr = $db->where('title','LIKE',"%$keyWord%")->page($page,$limit)->select();
                $count = $count->where('title','LIKE',"%$keyWord%")->count();
            }else{
                $list_arr = $db->page($page,$limit)->select();
                $count = $count->count();
            }

            foreach($list_arr as $key => $val){
                if($val['pid'] == 0){
                    $list_arr[$key]['pid_title'] = '顶级分类';
                }else{
                    foreach($list_arr as $k => $v){
                        if($val['pid'] == $v['id']){
                            $list_arr[$key]['pid_title'] = $v['title'];
                        }
                    }
                }
            }

            return ['code' => 0, 'count' => $count, 'data' => $list_arr, 'msg'=>''];
        }else{

            return view();
        }
    }

    /**
     * @author  ShuAnG
     * @createDate  2023-03-13
     * 考核栏目管理--添加
     * @return array
     */
    public function columnAdd(){
        if(request()->isAjax())
        {
            $data = input('post.');

            if(input('id')){
                $res = db('kpi_column')->where('id',input('id'))->update($data);
            }else{
                $res = db('kpi_column')->insert($data);
            }

            return $res?['msg'=>'操作成功','icon'=>1]:['msg'=>'操作失败','icon'=>2];
        }else{
            if(input('id')){

                $column_info = Db('kpi_column')->where('id',input('id'))->find();

                $this->assign([
                    'data' => $column_info,
                ]);
            }

            $column_arr = Db('kpi_column')->select();

            $this->assign([
                'column_list' => $column_arr,
            ]);

            return view();
        }
    }

    /**
     * @author  ShuAnG
     * @createDate  2023-03-14
     * 考核栏目管理--删除
     * @return array
     */
    public function columnDel(){
        if(input('id')){
            if(request()->isAjax()){
                $re = Db('kpi_column')->where('id',input('id'))->delete();

                return $re?['msg'=>'操作成功','icon'=>1]:['msg'=>'操作失败','icon'=>2];
            }
        }
    }

    /**
     * @author  ShuAnG
     * @createDate  2023-03-13
     * 考核栏目管理--状态
     * @return array
     */
    public function columnStatusChange(){
        if(input('id')){
            if(request()->isAjax()){
//                $re = Db('fixed_asset')->where('id',input('id'))->delete();
//                $re = 1;
                $db = Db('kpi_column');
                $column_info = $db->where('id',input('id'))->find();
//                echo "<pre>";print_r($re);die;
                $status = 0;
                if(!empty($column_info) && is_array($column_info)){
                    if($column_info['status'] == 0){
                        $status = 1;
                    }else{
                        $status = 0;
                    }

                    $re = $db->where('id',input('id'))->update(['status' => $status]);

                    return $re?['msg'=>'操作成功','icon'=>1]:['msg'=>'操作失败','icon'=>2];

                }else{
                    return ['msg'=>'参数错误','icon'=>2];
                }
            }
        }
    }

//--------------------------------------------------------------------------------

    /**
     * @author  ShuAnG
     * @createDate  2023-03-14
     * 考核内容管理--列表
     * @return mixed
     */
    public function columnExamContentList(){
        if(input()['limit'])
        {
            $page = input()['page']?:1;
            $limit = input()['limit']?:1;
            $db = Db('kpi_exam_content');
            $count = $db;

            if(input('keyword'))
            {
                $keyWord = input('keyword');
                //姓名、身份证、家庭住址、手机号、紧急联系人姓名、紧急联系人手机号
                $list_arr = $db->where('title','LIKE',"%$keyWord%")->page($page,$limit)->select();
                $count = $count->where('title','LIKE',"%$keyWord%")->count();
            }else{
                $list_arr = $db->page($page,$limit)->select();
                $count = $count->count();
            }

            //获取 栏目 列表
            $column_list = Db('kpi_column')->where('status',1)->select();

            foreach($list_arr as $key => $val){
                foreach($column_list as $k => $v){
                    if($val['kpi_column_id'] == $v['id']){
                        $list_arr[$key]['kpi_column_title'] = $v['title'];
                    }
                }
            }

            return ['code' => 0, 'count' => $count, 'data' => $list_arr, 'msg'=>''];
        }else{

            return view();
        }
    }

    /**
     * @author  ShuAnG
     * @createDate  2023-03-14
     * 考核内容管理--添加
     * @return array
     */
    public function columnExamContentAdd(){
        if(request()->isAjax())
        {
            $data = input('post.');

            if(input('id')){
                $res = db('kpi_exam_content')->where('id',input('id'))->update($data);
            }else{
                $res = db('kpi_exam_content')->insert($data);
            }

            return $res?['msg'=>'操作成功','icon'=>1]:['msg'=>'操作失败','icon'=>2];
        }else{
            if(input('id')){

                $column_info = Db('kpi_exam_content')->where('id',input('id'))->find();

                $this->assign([
                    'data' => $column_info,
                ]);
            }

            //获取 内容 列表
            $kpi_exam_content_list = Db('kpi_exam_content')->where('kpi_column_id','in','1,2,3,4,5,17,18')->select(); //只查找 部门、岗位、维度/类别、项目
            //获取 栏目 列表
            $kpi_column_list = Db('kpi_column')->where('status',1)->select();

            $this->assign([
                'kpi_column_list' => $kpi_column_list,
                'kpi_exam_content_list' => $kpi_exam_content_list,
            ]);

            return view();
        }
    }

    /**
     * @author  ShuAnG
     * @createDate  2023-03-14
     * 考核内容管理--删除
     * @return array
     */
    public function columnExamContentDel(){
        if(input('id')){
            if(request()->isAjax()){
                $re = Db('kpi_exam_content')->where('id',input('id'))->delete();

                return $re?['msg'=>'操作成功','icon'=>1]:['msg'=>'操作失败','icon'=>2];
            }
        }
    }

//------------------------------------------------------------------------------------------------------------

    /**
     * 营销考核
     * admin/Kpi/Marketing
     */
    public function marketing(){
        return view();
    }

//------------------------------------------------------------------------------------------------------------

    /**
     * @author  ShuAnG
     * @createDate  2023-03-15
     * 行政考核--列表
     * @return mixed
     */
    public function administration(){
        if(input()['limit'])
        {
            $page = input()['page']?:1;
            $limit = input()['limit']?:1;
            $db = Db('kpi_exams')->where('belong_to_department',3); //考核所属部门 1.运营 2.营销 3.行政 4.技术
            $count = $db;

            if(input('keyword'))
            {
                $keyWord = input('keyword');
                //姓名、身份证、家庭住址、手机号、紧急联系人姓名、紧急联系人手机号
                $list_arr = $db->where('title','LIKE',"%$keyWord%")->page($page,$limit)->select();
                $count = $count->where('title','LIKE',"%$keyWord%")->count();
            }else{
                $list_arr = $db->page($page,$limit)->select();
                $count = $count->count();
            }

            //获取 栏目 列表
            $column_list = Db('kpi_column')->where('status',1)->select();

            //获取 admin 列表
            $admin_list = Db('admin')->select();

            foreach($list_arr as $key => $val){

                $list_arr[$key]['add_time_date'] = date('Y-m-d H:i:s',$val['add_time']);
                $list_arr[$key]['start_time_date'] = date('Y-m-d H:i:s',$val['start_time']);
                $list_arr[$key]['end_time_date'] = date('Y-m-d H:i:s',$val['end_time']);

                switch($val['belong_to_department']){
                    case 1:
                        $list_arr[$key]['belong_to_department'] = '运营';
                        break;
                    case 2:
                        $list_arr[$key]['belong_to_department'] = '营销';
                        break;
                    case 3:
                        $list_arr[$key]['belong_to_department'] = '行政';
                        break;
                    case 4:
                        $list_arr[$key]['belong_to_department'] = '技术';
                        break;
                }

                $operator_id_arr = explode(',',$val['operator_id']);

                foreach($admin_list as $k => $v){
                    if($val['create_admin_id'] == $v['id']){
                        $list_arr[$key]['create_admin_name'] = $v['name'];
                    }

                    foreach($operator_id_arr as $kk => $vv){
                        if($v['id'] == $vv){
                            $list_arr[$key]['operator_name'] .= $v['name'] . ',';
                        }
                    }
                }

            }

            return ['code' => 0, 'count' => $count, 'data' => $list_arr, 'msg'=>''];
        }else{

            return view();
        }
    }

    /**
     * @author  ShuAnG
     * @createDate  2023-03-15
     * 行政考核--预览
     * @return mixed
     */
    public function administrationView(){
        if(input('id')){
            $kpi_exams_info = Db('kpi_exams')->where('id',input('id'))->find();
            $kpi_column_arr = Db('kpi_column')->where('id','in',$kpi_exams_info['kpi_column_id'])->select();
            $kpi_exam_content_arr = Db('kpi_exam_content')->where('id','in',$kpi_exams_info['kpi_exam_content_id'])->select();

            $col_arr = explode(',',$kpi_exams_info['kpi_column_id']);
            $row_arr = explode(',',$kpi_exams_info['kpi_exam_content_id']);

            $exclude_col = [1,2,17,18];//排除 1.部门 2.岗位 17.绩效工资(底部) 18.备注(底部)
            $row_tem = 0;
            foreach($col_arr as $key => $val){
                if(in_array($val,$exclude_col)){
                    unset($col_arr[$key]);
                    $row_tem++;
                }
            }

            $col_count = count($col_arr); // 表格 列 col  的总数

            $row_count = 0;
            $is_have_categorize = false; // 是否有 分类/维度 栏目  kpi_column_id = 3||4
            $categorize_arr = [];   // 分类/维度 数组
            foreach($kpi_exam_content_arr as $key => $val){
                if($val['kpi_column_id'] == 5){ // kpi_column_id=5 为项目 数量 （计算 row 数量 = 项目数量 + $row_tem）
                    $row_count++;
                }

                if($val['kpi_column_id'] == 3 || $val['kpi_column_id'] == 4){   // 是否有 分类/维度 栏目  kpi_column_id = 3||4
                    $is_have_categorize = true;
                    $categorize_arr[] = $val;
                }
            }

            $row_count = $row_count + $row_tem;// 表格 行 row  的总数  (row 数量 = 项目数量 + $row_tem)

            switch($kpi_exams_info['belong_to_department']){
                case 1:
                    $kpi_exams_info['belong_to_department_name'] = '运营';
                    break;
                case 2:
                    $kpi_exams_info['belong_to_department_name'] = '营销';
                    break;
                case 3:
                    $kpi_exams_info['belong_to_department_name'] = '行政';
                    break;
                case 4:
                    $kpi_exams_info['belong_to_department_name'] = '技术';
                    break;
            }

            $kpi_exams_info['add_time_date'] = date('Y-m-d H:i:s',$kpi_exams_info['add_time']);
            $kpi_exams_info['start_time_date'] = date('Y-m-d H:i:s',$kpi_exams_info['start_time']);
            $kpi_exams_info['end_time_date'] = date('Y-m-d H:i:s',$kpi_exams_info['end_time']);

            //获取 列 col 的名称
            $col_name_arr = [];
            foreach($kpi_column_arr as $key => $val){
                foreach($col_arr as $k => $v){
                    if($val['id'] == $v){
                        $col_name_arr[$k]['title'] = $val['title'];
                        $col_name_arr[$k]['id'] = $val['id'];
                    }
                }
            }

            //------------------拼接内容start------------------
            $content = [];
            $is_have_categorize = false;

            $kpi_exam_content_arr_all = Db('kpi_exam_content')->select();
            //判断是否 有 分类/维度
            if($is_have_categorize){
                foreach($kpi_exam_content_arr as $key => $val){
                    foreach($categorize_arr as $k => $v){
                        if($val['kpi_column_id'] == 5 && $val['pid'] == $v['id']){
                            $categorize_arr[$k]['project'][] = $val;
                        }
                    }
                }

                foreach($categorize_arr as $key => $val){
                    $categorize_arr[$key]['row_sum'] = count($val['project']);
                    foreach($val['project'] as $k => $v){
                        foreach($kpi_exam_content_arr_all as $kk => $vv){
                            if($vv['pid'] == $v['id']){
                                $categorize_arr[$key]['project'][$k]['child'][] = $vv;
                            }
                        }
                    }
                }

                foreach($kpi_exam_content_arr_all as $key => $val){
                    foreach($categorize_arr as $k => $v){
                        if($v['id'] == $val['id']){
                            $content[] = $val;
                        }
                        foreach($v['project'] as $kk => $vv){

                        }
                    }
                }

//                $content = $categorize_arr;

            }else{
                $project_arr = [];
                foreach($kpi_exam_content_arr as $key => $val){
                    if($val['kpi_column_id'] == 5){
                        $project_arr[] = $val;
                    }
                }

                foreach($project_arr as $key => $val){
                    $content[$key][] = $val;
                    foreach($kpi_exam_content_arr_all as $k => $v){
                        if($val['id'] == $v['pid']){
                            $project_arr[$key]['child'][] = $v;
                            $content[$key][] = $v;
                        }
                    }
                }

//                $content = $project_arr;

            }

            //------------------拼接内容end------------------

//            echo "<pre>";
//            print_r($kpi_exam_content_arr);
//            die;

            $row_foot = [];
            foreach($kpi_exam_content_arr as $key => $val){
                if($val['kpi_column_id'] == 17 || $val['kpi_column_id'] == 18){ // 表格 底部 17.绩效工资(底部)|| 18.备注(底部)
                    $row_foot[] = $val;
                }
            }

//            echo "<pre>";
//            print_r($foot);
//            die;






            $data = [];
            $data['col_count'] = $col_count;
            $data['row_count'] = $row_count;
            $data['belong_to_department_name'] = $kpi_exams_info['belong_to_department_name'];
            $data['start_time_date'] = $kpi_exams_info['start_time_date'];
            $data['end_time_date'] = $kpi_exams_info['end_time_date'];
            $data['title'] = $kpi_exams_info['title'];
            $data['col_name'] = $col_name_arr;
            $data['row_content'] = $content;
            $data['row_foot'] = $row_foot;

//            echo "<pre>";
//            print_r($data);
//            die;

            $this->assign([
                'data' => $data
            ]);

            return view();
        }
    }

    /**
     * @author  ShuAnG
     * @createDate  2023-03-14
     * 考核内容管理--添加
     * @return array
     */
    public function administrationAdd(){
        if(request()->isAjax())
        {
            $post = input('post.');

//            echo "<pre>";
//            print_r($post);
//            die;

            $column_arr = [];//栏目 数组
            $content_arr = [];//栏目 内容 数组
            $admin_arr = [];//admin 考核人员 数组

            foreach($post['column'] as $key => $val){
                if(strpos($val,'-')){
                    $content_arr[] = substr($val,strpos($val,'-')+1);
                }elseif(strpos($val,'*')){
                    $admin_arr[] = substr($val,strpos($val,'*')+1);
                }else{
                    $column_arr[] = $val;
                }
            }

            $column_str = implode(',',$column_arr);
            $content_str = implode(',',$content_arr);
            $admin_str = implode(',',$admin_arr);

//            echo "<pre>";
//            print_r($column_str);
//            echo "<br>";
//            print_r($content_str);
//            echo "<br>";
//            print_r($admin_str);
//            die;


            $title = $post['title'];

            $start_date = $post['start_date'];
            $end_date = $post['end_date'];

            $create_id = session('uid','','admin');

            $data = [];
            $data['title'] = $title;
            $data['kpi_column_id'] = $column_str;
            $data['kpi_exam_content_id'] = $content_str;
            $data['add_time'] = time();
            $data['start_time'] = strtotime($start_date . '00:00:00');
            $data['end_time'] = strtotime($end_date . '23:59:59');
            $data['create_admin_id'] = $create_id;
            $data['operator_id'] = $admin_str;
            $data['belong_to_department'] = 3;//考核所属部门 1.运营2.营销3.行政4.技术
            $data['status'] = 1;//考核状态 1.正常 2.过期 3.未开启

//            tp_kpi_exam
//
//id
//title
//kpi_column_id
//kpi_exam_content_id
//add_time
//start_time
//end_time
//create_admin_id
//operator_id
//belong_to_department
//status
//
//
//int
//varchar
//varchar
//varchar
//int
//int
//int
//int
//varchar
//tinyint
//tinyint



//            echo "<pre>";
//            print_r($data);
//            die;
//            $asd = db('kpi_exam_content')->getDbError();
//            $qwe = db('kpi_exam_content')->getError();
//
//            echo "<pre>";
//            print_r($asd);
//            echo "<br>";
//            print_r($qwe);
//            die;

            if(input('id')){
                $res = db('kpi_exams')->where('id',input('id'))->update($data);
            }else{
                $res = db('kpi_exams')->insert($data);
            }

            return $res?['msg'=>'操作成功','icon'=>1]:['msg'=>'操作失败','icon'=>2];
        }else{
            if(input('id')){

                $column_info = Db('kpi_exam_content')->where('id',input('id'))->find();

                $this->assign([
                    'data' => $column_info,
                ]);
            }

            //获取 内容 列表
            $kpi_exam_content_list = Db('kpi_exam_content')->where('kpi_column_id','in','1,2,3,4,5,17,18')->select(); //只查找 部门、岗位、维度/类别、项目
            //获取 栏目 列表
            $kpi_column_list = Db('kpi_column')->where('status',1)->select();
            //获取 行政 admin ID
            $admin_list = Db('admin')->where('group_id',8)->where('status',1)->field('id,name')->select();

            $this->assign([
                'kpi_column_list' => $kpi_column_list,
                'kpi_exam_content_list' => $kpi_exam_content_list,
                'admin_list' => $admin_list,
            ]);

            return view();
        }
    }

//------------------------------------------------------------------------------------------------------------

    /**
     * 技术考核
     * admin/Kpi/technology
     */
    public function technology(){
        return view();
    }




}